<template>
	<div class="box-container">
		<div class="header-content">
			<span class="font_size20">{{ titleName + '单' }}</span>
		</div>
		<div class="body-content">
			<OrderStatusBar :detailData="detailData" :basicInfo="basicInfo" :titleUnitName="titleUnitName"
				@addCompany="addCompany" @selectStore="selectStore" :tabType="tabType" :storeList="deStoreList" />
			<BascInfo :detailData="detailData" @handleTxtLs="handleTxtLs" />
			<GoodCards :detailData="detailData" :titleName="titleName" :tabType="tabType" />
			<div style="height: 50px;"></div>
		</div>
		<PopCustomerSelect ref="popCustomerSelect" @getCustomerData="getCustomerData" />
		<PopSupperSelect ref="PopSupperSelectSelectRef" @getCustomerData="getSupperData" />
		<TxtLsDrawer ref="txtLsDrawerRef" :txt_ls="detailData.txt_ls" :id="detailData.id" />
		<LogLsDrawer ref="logLsDrawerRef" :id="detailData.id"></LogLsDrawer>
		<div class="footer-content" v-if="operations.length > 0">
			<footer-bottom :operations="operations" @operation="handleOperation" :type="'warehouseManage'" />
		</div>
		<ayjDialog ref="ayjBatchDeliveryDialogRef" :slotFooter="true" width="50%" top="3vh" :title="titleName + '分批操作'">
			<BatchDelivery :list="sku_ls" :store_ls="store_ls" @carCallBack="BatchCarCallBack" />
			<div slot="footer" class="flex_center">
				<el-button size="mini" @click="handleCancel">取 消</el-button>
				<el-button size="mini" type="primary" @click="handleFpckSubmit">立即{{ titleName }}</el-button>
			</div>
		</ayjDialog>
	</div>
</template>

<script setup>
import { ref, onMounted, defineProps, defineEmits, getCurrentInstance, watch, computed, nextTick } from '@vue/composition-api'
const { proxy } = getCurrentInstance()
import config from "@/js/conf/Config.js"
import FooterBottom from "@/components/commV2/FooterBottom/index.vue";
import PopCustomerSelect from "@/components/appointment/popCustomerSelect.vue";
import PopSupperSelect from "@/components/appointment/popSupperSelect.vue";
import TxtLsDrawer from "@/pages/warehouseManage/orderReceipt/components/txtLsDrawer.vue";
import BascInfo from "@/pages/warehouseManage/orderReceipt/components/bascInfo.vue";
import OrderStatusBar from "@/pages/warehouseManage/orderReceipt/components/orderStatusBar.vue";
import GoodCards from "@/pages/warehouseManage/orderReceipt/components/goodCards.vue";
import BatchDelivery from "@/pages/warehouseManage/orderReceipt/components/batchDelivery.vue";
import LogLsDrawer from "@/pages/warehouseManage/orderReceipt/components/logLsDrawer.vue";
import { useOrderReceiptState } from '@/pages/warehouseManage/hooks/useOrderReceiptState.js'
import accessCtrl from "@/js/limit/AccessCtrl.js"; // 检测权限

const {
	tabType,
	query,
	box_index_key,
	detailData,
	getEventInfo,
	isEdit,
	isCartAddFrom,
	getEventLs,
	selectedIndex,
	getStoreList,
	deStoreList,
	isToDoModal
} = useOrderReceiptState()

// into_warehouse  入库单
// out_warehouse  出库单
// transfer_warehouse  调拨单
const titleName = computed(() => {
	return tabType.value == 'into_warehouse' ? '入库' :
		tabType.value == 'transfer_warehouse' ? '调拨' :
			tabType.value == 'out_warehouse' ? '出库' : ''
})

const titleUnitName = computed(() => {
	return tabType.value == 'into_warehouse' ? '来货' :
		tabType.value == 'transfer_warehouse' ? '调拨' :
			tabType.value == 'out_warehouse' ? '收货' : ''
})

const basicInfo = computed(() => {
	const customerInfo = detailData.value?.customer_info;
	const upperInfo = detailData.value?.supper_info;
	if (customerInfo && Object.keys(customerInfo).length > 0) {
		return customerInfo;
	}
	if (upperInfo && Object.keys(upperInfo).length > 0) {
		return upperInfo;
	}
	return null;
});

// type  1 出库单；2 入库单；3调拨单；4盘点单；5报损单
// st  	 1待确认(未启用)；2已确认；3待出入库；4已出入库；21草稿单；22已作废
// 创建一个ref来存储操作数组
const operations = ref([])
const fetchOperations = async () => {
	let type = Number(detailData.value.type)
	let st = Number(detailData.value.st)
	switch (type) {
		case 1: // 1 出库单
			switch (st) {
				case 3: // 待出入库
					operations.value = [
						{ text: '作废', type: 'scrap', class: 'danger', permission: await accessCtrl.getStorekeeperVoidLimit() },
						{ text: '操作记录', type: 'record', class: '', permission: true },
						{ text: '抄单', type: 'copy', class: 'orange', permission: true },
						{ text: '分批出库', type: 'fpck', class: 'primary', permission: true },
						{ text: '整单出库', type: 'zdck', class: 'primary', permission: true },
					]
					break
				case 4: // 已出入库
					operations.value = [
						{ text: '作废', type: 'scrap', class: 'danger', permission: await accessCtrl.getStorekeeperVoidLimit() },
						{ text: '操作记录', type: 'record', class: '', permission: true },
						{ text: '抄单', type: 'copy', class: 'orange', permission: true },
					]
					break
				case 21: // 草稿单
					operations.value = [
						{ text: '删除', type: 'del', class: 'danger', permission: await accessCtrl.getStorekeeperDeleteLimit() },
						{ text: '编辑', type: 'edt', class: 'primary', permission: await accessCtrl.getStorekeeperEditLimit() },
					]
					break
				case 22: // 已作废
					operations.value = [
						{ text: '删除', type: 'del', class: 'danger', permission: await accessCtrl.getStorekeeperDeleteLimit() },
					]
					break
				default:
					operations.value = []
			}
			break
		case 2: // 入库单
			switch (st) {
				case 3: // 待出入库
					operations.value = [
						{ text: '作废', type: 'scrap', class: 'danger', permission: await accessCtrl.getStorekeeperVoidLimit() },
						{ text: '操作记录', type: 'record', class: '', permission: true },
						{ text: '抄单', type: 'copy', class: 'orange', permission: true },
						{ text: '分批入库', type: 'fprk', class: 'primary', permission: true },
						{ text: '整单入库', type: 'zdrk', class: 'primary', permission: true },
					]
					break
				case 4: // 已出入库
					operations.value = [
						{ text: '作废', type: 'scrap', class: 'danger', permission: await accessCtrl.getStorekeeperVoidLimit() },
						{ text: '操作记录', type: 'record', class: '', permission: true },
						{ text: '抄单', type: 'copy', class: 'orange', permission: true },
					]
					break
				case 21: // 草稿单
					operations.value = [
						{ text: '删除', type: 'del', class: 'danger', permission: await accessCtrl.getStorekeeperDeleteLimit() },
						{ text: '编辑', type: 'edt', class: 'primary', permission: await accessCtrl.getStorekeeperEditLimit() },
					]
					break
				case 22: // 已作废
					operations.value = [
						{ text: '删除', type: 'del', class: 'danger', permission: await accessCtrl.getStorekeeperDeleteLimit() },
					]
					break
				default:
					operations.value = []
			}
			break
		case 3: // 调拨单
			switch (st) {
				case 3: // 待出入库
					operations.value = [
						{ text: '作废', type: 'scrap', class: 'danger', permission: await accessCtrl.getStorekeeperVoidLimit() },
						{ text: '操作记录', type: 'record', class: '', permission: true },
						{ text: '抄单', type: 'copy', class: 'orange', permission: true },
						{ text: '立即调库', type: 'ljdk', class: 'primary', permission: true },
					]
					break
				case 4: // 已出入库
					operations.value = [
						{ text: '作废', type: 'scrap', class: 'danger', permission: await accessCtrl.getStorekeeperVoidLimit() },
						{ text: '操作记录', type: 'record', class: '', permission: true },
						{ text: '抄单', type: 'copy', class: 'orange', permission: true },
					]
					break
				case 21: // 草稿单
					operations.value = [
						{ text: '删除', type: 'del', class: 'danger', permission: await accessCtrl.getStorekeeperDeleteLimit() },
						{ text: '编辑', type: 'edt', class: 'primary', permission: await accessCtrl.getStorekeeperEditLimit() },
					]
					break
				case 22: // 已作废
					operations.value = [
						{ text: '删除', type: 'del', class: 'danger', permission: await accessCtrl.getStorekeeperDeleteLimit() },
					]
					break
				default:
					operations.value = []
			}
			break
		default:
			operations.value = []
	}
}

watch([() => detailData.value.type, () => detailData.value.st], async () => {
	if (detailData.value.type && detailData.value.st) {
		await fetchOperations()
	}
}, { immediate: true })

const handleOperation = (type) => {
	switch (type) {
		case 'edt':
			edtHandle()
			break;
		case 'stop':
			stopFun('stop')
			break;
		case 'zdck':
			zdcrkFun({ act: 'inout_all' })
			break;
		case 'zdrk':
			zdcrkFun({ act: 'inout_all' })
			break;
		case 'fpck':
			onView()
			break;
		case 'fprk':
			onView()
			break;
		case 'record':
			openHandle()
			break;
		case 'copy':
			copyHandle()
			break;
		case 'del':
			delHandle()
			break;
		case 'scrap':
			scrapHandle()
			break;
		case 'ljdk':
			ljdkFun()
			break;
	}
};

// 立即调拨
const ljdkFun = () => {
	proxy.$confirm('确定要整单调拨吗?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(() => {
		submitOrderAct({ ...detailData.value, act: 'inout_all' })
	})
}

// 作废
const scrapHandle = () => {
	proxy.$confirm('确定作废该订单吗?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(() => {
		submitOrderAct({ ...detailData.value, act: 'scrap' })
	})
}

// 抄单操作
const delHandle = () => {
	proxy.$confirm('确定删除该订单吗?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(() => {
		submitOrderAct({ ...detailData.value, act: 'del' })
	})
}

// 编辑操作
const edtHandle = () => {
	proxy.$confirm('确定要编辑该草稿单吗?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(() => {
		submitOrderCopyEdit({ act: 2, ...detailData.value })
	})
}

// 抄单操作
const copyHandle = () => {
	proxy.$confirm('该操作将清空内待开单商品,确定要复制订单吗?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(() => {
		submitOrderCopyEdit({ act: 1, ...detailData.value })
	})
}
// 提交抄单操作
const submitOrderCopyEdit = async (data) => {
	let param = {
		...data,
		odid: detailData.value.id,
	}
	try {
		let res = await proxy.$api({ url: config.ck_order_order_copy, data: param })
		if (res.status == 1) {
			proxy.$message({
				message: '操作成功',
				type: 'success',
			})
			setTimeout(() => {
				selectedIndex.value = null
				isCartAddFrom.value = true
			}, 1200)
		} else {
			proxy.$message({
				message: res.msg || '操作失败',
				type: 'error',
			})
		}
	} catch (error) {
		proxy.$message({
			message: error?.message || '操作失败',
			type: 'error',
		})
	} finally { }
}

// 操作记录
const logLsDrawerRef = ref(null)
const openHandle = (row) => {
	logLsDrawerRef.value.open()
}

// 整批出单
const zdcrkFun = (obj) => {
	const detailInfo = {
		...detailData.value
	}
	const type = query.value.type // 1出库单；2入库单；3调拨单；4盘点单；5报损单
	let isCheckSta = checkIofn()
	if ((type == 1 || type == 2) && isCheckSta) {
		let params = {
			...detailInfo,
		}
		submitOrderAct({ act: obj.act, ...params })
	} else if (type == 3) {

	}
}

const checkIofn = () => {
	const detailInfo = {
		...detailData.value
	}
	if (!basicInfo.value) {
		proxy.$message({
			message: '请先添加单位',
			type: 'error',
		})
		return false
	}
	if (!detailInfo.store) {
		proxy.$message({
			message: '请先选择仓库',
			type: 'error',
		})
		return false
	}
	return true
}

// 分批出库
const ayjBatchDeliveryDialogRef = ref(null)
const onView = () => {
	let isCheckSta = checkIofn()
	if (!isCheckSta) {
		return
	}
	ckOrderOrder2inout((data) => {
		console.log("data=", data)
		ayjBatchDeliveryDialogRef.value.open()
	})
}
const sku_num = ref([])
const BatchCarCallBack = (list) => {
	sku_num.value = list.map(vm => {
		return {
			...vm,
			num: vm.dri_number_not
		}
	})
}

// 分批出库
const handleFpckSubmit = () => {
	submitOrderAct({ ...detailData.value, act: 'inout_part', sku_num: sku_num.value })
}
// 添加单位
const getCustomerData = (data) => {
	submitOrderAct({ customerid: data.id, act: 'custom_add', ...data })
}
// 选择供应商
const getSupperData = (data) => {
	submitOrderAct({ suppid: data.id, act: 'supp_add', ...data })
}

const handleCancel = () => { ayjBatchDeliveryDialogRef.value.close() }
// 添加单位地址 
const addCompany = () => {
	proxy.$confirm(`添加${titleUnitName.value}单位后不可修改，是否继续?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		if (tabType.value == 'into_warehouse') {
			proxy.$refs.PopSupperSelectSelectRef.initData();
		} else if (tabType.value == 'out_warehouse') {
			proxy.$refs.popCustomerSelect.initData();
		}
	}).catch(() => {
	});
}

// 添加仓库
const selectStore = (e) => {
	detailData.value.store = e.name
	detailData.value.storeid = e.id
}

// 更新待出库订单
const submitOrderAct = async (data) => {
	let param = {
		...data,
		odid: detailData.value.id,
		pfrom: 0,
		pnum: 0,
		st: detailData.value?.st
	}
	try {
		let res = await proxy.$api({ url: config.ck_order_order_act, data: param })
		if (res.status == 1) {
			proxy.$message({
				message: '操作成功',
				type: 'success',
			})
			if (isToDoModal.value) {
				getEventLs(true)
				if (data.act == 'inout_part') {
					handleCancel()
				}
			} else {
				if (data.act == 'inout_all') {
					isEdit.value = false
					isCartAddFrom.value = false
					query.value.st = '4'
					box_index_key.value = '4'
					getEventLs(true)
				} else if (data.act == 'del') {
					getEventLs(true)
				} else if (data.act == 'scrap') {
					isEdit.value = false
					isCartAddFrom.value = false
					query.value.st = '22'
					box_index_key.value = '22'
					getEventLs(true)
				} else {
					getEventInfo()
				}
				if (data.act == 'inout_part') {
					handleCancel()
				}
			}
		} else {
			proxy.$message({
				message: res.msg || '操作失败',
				type: 'error',
			})
		}
	} catch (error) {
		proxy.$message({
			message: error?.message || '操作失败',
			type: 'error',
		})
	} finally { }
}

// 备注
const handleTxtLs = () => {
	proxy.$refs.txtLsDrawerRef.open()
}

// 查询待出库商品列表
const order2inoutData = ref({})
const sku_ls = ref([])
const store_ls = ref([])
const ckOrderOrder2inout = async (callBack) => {
	let param = {
		...detailData.value,
		odid: detailData.value.id,
		st: detailData.value?.st
	}
	try {
		let res = await proxy.$api({ url: config.ck_order_order_2inout, data: param })
		if (res.status == 1) {
			callBack(res.data)
			order2inoutData.value = res.data
			sku_ls.value = res.data?.sku_ls.map(vm => {
				return {
					...vm,
					dri_number_not: 0,
				}
			})
			store_ls.value = res.data?.store_ls
		} else {
			proxy.$message({
				message: res.msg || '暂无数据',
				type: 'error',
			})
		}
	} catch (error) {
		proxy.$message({
			message: error?.message || '暂无数据',
			type: 'error',
		})
	} finally { }
}

// 详情页面 获取仓库列表
// onMounted(() => {
// })

getStoreList()

defineExpose({})

</script>

<style lang="scss" scoped>
.box-container {
	height: 100%;
	overflow: hidden;
	display: flex;
	flex-direction: column;

	.header-content {
		width: 100%;
		height: 40px;
		border-bottom: 2px solid #E4E7ED;
		margin-bottom: 5px;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.body-content {
		padding-right: 10px;
		flex: 1;
		overflow: hidden;
		overflow-y: auto;
	}

	.footer-content {
		height: 60px;
	}
}
</style>